package com.dingding.service;

import cn.hutool.json.JSONUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.dingding.entity.UserSession;
import java.util.Calendar;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class JwtService {

    private static String SECRET_KEY = "R4I2NEB7P1LQQWA1LTJ2OCB8SC2NWMW0";

    private final RedisService redisService;

    public String getToken(UserSession user) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 1);

        JWTCreator.Builder builder = JWT.create();
        builder.withClaim("user", JSONUtil.toJsonStr(user));

        String sign = builder.withExpiresAt(cal.getTime()).sign(Algorithm.HMAC256(SECRET_KEY));
        redisService.setToken(user.getUserId(), sign);
        return sign;
    }

    public static DecodedJWT verify(String token) {
        JWTVerifier build = JWT.require(Algorithm.HMAC256(SECRET_KEY)).build();
        return build.verify(token);
    }

    public UserSession getUser(String token) {
        Claim user = JWT.decode(token).getClaim("user");
        return JSONUtil.toBean(user.asString(), UserSession.class);
    }
}
